<template>
  <!--遮罩-->
  <div class="loading" v-if="displaymode == 2 || displaymode == 3"></div>
  <div class="iframe-wrapper" :class="{ 'is-iframe': isInIframe }" :style="iframeStyle">
  <el-card class="main_top" shadow="hover">
    <div class="toolbar-section">
      <div class="logo-section">
        <img src="/images/logo.png" alt="Logo" class="logo-image" />
        <span class="logo-text">组态管理平台</span>
      </div>
      <div class="left-actions">
        <el-button type="primary" @click="loadExample('')" :icon="DocumentAdd">
          新建模板
        </el-button>
        <el-button type="info" @click="switchMode(3)" :icon="List">
          模板列表
        </el-button>
        <el-button
          v-if="displaymode == 0"
          type="success"
          @click="downloadSvgData"
          :icon="Download"
        >
          下载数据
        </el-button>
        <el-button
          v-if="displaymode == 0"
          type="success"
          @click="downloadSvgDomData"
          :icon="Document"
        >
          下载SVG
        </el-button>
        <el-button
          v-if="displaymode == 0"
          type="warning"
          @click="switchMode(2)"
          :icon="Upload"
        >
          发布
        </el-button>
      </div>
      <div class="right-config">
        <el-form inline>
          <el-form-item label="画布宽度">
            <el-input-number v-model="tWidth" :min="100" :max="5000" />
          </el-form-item>
          <el-form-item label="画布高度">
            <el-input-number v-model="tHeight" :min="100" :max="5000" />
          </el-form-item>
          <el-form-item label="画布颜色">
            <el-color-picker show-alpha v-model="tBackgroundColor" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveData()" :icon="DocumentChecked">
              保存配置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </el-card>

  <div class="main">
    <div class="editor-container">
      <n-message-provider>
        <svg-editor
          ref="ref_svgedit"
          :component_infos="component_infos"
          @saveSvgInfo="saveSvgInfo"
          :svgCanvas="{ width: tWidth, height: tHeight }"
          :tBackgroundColor="tBackgroundColor"
        ></svg-editor>
      </n-message-provider>
    </div>
    <div v-if="displaymode == 1" class="editor-container">
      <svg-prview
        :component_infos="component_infos"
        :svg_data="prview_data"
        :svgCanvas="{ width: tWidth, height: tHeight }"
        :tBackgroundColor="tBackgroundColor"
      ></svg-prview>
    </div>
    <!-- 保存组态弹窗 -->
    <el-dialog
      v-model="saveDialogVisible"
      title="💾 保存组态"
      :width="'500px'"
      :before-close="handleSaveClose"
      destroy-on-close
      :modal-append-to-body="false"
      :lock-scroll="true"
      :close-on-click-modal="false"
      :show-close="true"
      center
      class="save-db-dialog"
    >
      <template #default>
        <n-message-provider>
          <save-db
            :svg_data="savesvg_data"
            :tId="tId"
            :tName="tName"
            :tTopic="tTopic"
            :width="tWidth"
            :height="tHeight"
            :tBackgroundColor="tBackgroundColor"
            @closePageBack="handleSaveClose"
          ></save-db>
        </n-message-provider>
      </template>
    </el-dialog>
    <!-- 组态图列表弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="📋 组态图列表"
      :width="'80%'"
      :before-close="handleClose"
      destroy-on-close
      :modal-append-to-body="false"
      :lock-scroll="true"
      :close-on-click-modal="false"
      :show-close="true"
      class="template-list-dialog"
    >
      <template #default>
        <div style="max-height: 70vh; overflow: hidden;">
          <svg-list @closePageBack="closePageBack" @closeDialog="handleClose"></svg-list>
        </div>
      </template>
    </el-dialog>
  </div>
  </div>
</template>

<script setup lang="ts">
import SvgEditor from "../components/SvgEditor.vue";
import SvgPrview from "../components/SvgPrview.vue";
import SaveDb from "../components/SvgDb/SaveDb.vue";
import SvgList from "../components/SvgDb/SvgList.vue";
import { NMessageProvider } from "naive-ui";
import axios from "axios";
import { ref, inject } from "vue";
import { DocumentAdd, List, Download, Document, Upload, DocumentChecked } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const mqtt: any = inject("$m");

// 检测是否在 iframe 中
const isInIframe = ref(window.self !== window.top);

// 计算 iframe 缩放比例
const iframeStyle = ref({});

const component_infos = ref([]);
const ref_svgedit = ref();
//要预览的数据
const prview_data = ref<any>([]);
//定义一个变量用来控制演示模式 0为绘制模式 1为预览模式 2数据保存到数据库
const displaymode = ref(0);
const dialogVisible = ref(false);
const saveDialogVisible = ref(false);
//定义一个变量用来接收保存的svg数据
const savesvg_data = ref([]);
//定义一个变量用来接收保存的svgdom数据
const savesvg_dom_data: any = ref(null);
//保存用于传递到数据库操作页面的数据
let tId = ref(""),
  tName = ref(""),
  tTopic = ref("frontend/#");
let tBackgroundColor = ref("#00000000");
let tWidth = ref(1920);
let tHeight = ref(960);
//数据库保存数据完成（保留用于兼容）
const closePageBack = (backData: any) => {
  displaymode.value = 0;

  if (backData != null) {
    var svgdata = backData.t_jsondata;
    var t_jsondata = JSON.parse(svgdata);
    tId.value = backData.t_id;
    tName.value = backData.t_name;
    tTopic.value = backData.t_topic;
    tWidth.value = backData.t_width;
    tHeight.value = backData.t_height;
    tBackgroundColor.value = backData.t_background_color;
    (ref_svgedit.value as any).setSvgLists(t_jsondata);
  }
};

//获取组件列表
axios.get("json/InterfaceReturn.json").then((res) => {
  component_infos.value = res.data;
});

//定义一个方法 接收组件保存传过来的数据
const saveSvgInfo = (svg_data: any, svg_dom: any) => {
  savesvg_data.value = svg_data;
  savesvg_dom_data.value = svg_dom;
};
//保存SVG
const saveData = () => {
  (ref_svgedit.value as any).saveSvgInfo();
};
const downloadSvgData = () => {
  if (savesvg_data.value == null) {
    alert("请先保存绘制数据");
    return;
  }
  let datastr =
    "data:text/json;charset=utf-8," +
    encodeURIComponent(JSON.stringify(savesvg_data.value));
  let download = document.createElement("a");
  download.setAttribute("href", datastr);
  download.setAttribute("download", `${new Date().getTime()}.json`);
  download.click();
  download.remove();
};
//下载SVG
const downloadSvgDomData = () => {
  if (savesvg_dom_data.value == null) {
    alert("请先保存绘制数据");
    return;
  }
  let datastr =
    "data:text;charset=utf-8," + encodeURIComponent(savesvg_dom_data.value.outerHTML);
  let download = document.createElement("a");
  download.setAttribute("href", datastr);
  download.setAttribute("download", `${new Date().getTime()}.html`);
  download.click();
  download.remove();
};

const switchMode = (currVal: any) => {
  if (currVal == 1) {
    if (savesvg_dom_data.value == null) {
      alert("请先保存绘制数据");
      return;
    }
    mqtt_info();
  } else if (currVal == 2) {
    //保存数据库
    if (savesvg_dom_data.value == null) {
      alert("请先保存绘制数据");
      return;
    }
    // 打开保存弹窗
    saveDialogVisible.value = true;
    return;
  } else if (currVal == 3) {
    //模板列表弹窗
    dialogVisible.value = true;
    return;
  }
  displaymode.value = currVal;
};

const handleClose = () => {
  dialogVisible.value = false;
};

const handleSaveClose = (backData: any = null) => {
  saveDialogVisible.value = false;
  displaymode.value = 0;
  
  if (backData != null && backData.t_jsondata) {
    var svgdata = backData.t_jsondata;
    try {
      var t_jsondata = JSON.parse(svgdata);
      tId.value = backData.t_id;
      tName.value = backData.t_name;
      tTopic.value = backData.t_topic;
      tWidth.value = backData.t_width;
      tHeight.value = backData.t_height;
      tBackgroundColor.value = backData.t_background_color;
      (ref_svgedit.value as any).setSvgLists(t_jsondata);
    } catch (error) {
      console.error('解析 SVG 数据失败:', error);
      ElMessage.error('加载组态图数据失败');
    }
  }
};

//载入模板，当参数为空是新建模板
const loadExample = (file_name: string) => {
  if ("" == file_name) {
    (ref_svgedit.value as any).setSvgLists([]);
    (tId.value = ""), (tName.value = ""), (tTopic.value = "frontend/#");
    (tWidth.value = 1920), (tHeight.value = 960);
    displaymode.value = 0;
  } else {
    axios.get(file_name).then((res) => {
      (ref_svgedit.value as any).setSvgLists(res.data);
    });
  }
};

//有动态效果的文字SVG
const TextSvgList = ref<any>([]);
//有动态效果的非文字SVG
const allActiveList = ref<any>([]);
//获取本页面默认数据列表
const getDefaultConfig = () => {
  prview_data.value = [];
  prview_data.value = savesvg_data.value;
  let temp: Array<any> = [...prview_data.value];
  //找到所有的文字
  TextSvgList.value = temp.filter((f) => f.active_type == "text" && f.nodeKey !== "");
  allActiveList.value = temp.filter((f) => f.nodeKey !== "");
};

const mqtt_info = () => {
  getDefaultConfig();
  mqtt.message_callback(tTopic, (topic: string, payload: Buffer) => {
    //非预览模式，不显示动态数据
    if (displaymode.value != 1) {
      return;
    }
    let payloadData = JSON.parse(payload.toString());
    var keys = Object.keys(payloadData);
    // console.log(TextSvgList.value);

    //文字显示
    TextSvgList.value.forEach((textSvg) => {
      for (let i = 0; i < keys.length; i++) {
        if (textSvg.nodeKey.trim() == keys[i].trim()) {
          (textSvg as any).extend_attr.text.val = payloadData[keys[i]];
          return;
        }
      }
    });

    //动态效果
    allActiveList.value.forEach((allSvg) => {
      for (let i = 0; i < keys.length; i++) {
        if (allSvg.nodeKey.trim() == keys[i].trim()) {
          let value = payloadData[keys[i]];
          //变色特性
          if (allSvg.active.hasOwnProperty("active_color")) {
            allSvg.active.active_color.alarm.forEach((kk) => {
              if (eval(kk.expression.val)) {
                allSvg.extend_attr.color.val = kk.color.val;
              }
            });
          }

          //switch效果状态
          if (allSvg.active.hasOwnProperty("active_switch")) {
            allSvg.active.active_switch.alarm.forEach((kk) => {
              if (eval(kk.expression.val)) {
                allSvg.extend_attr.switch.val.selectval = kk.switch.val.selectval;
              }
            });
          }

          //旋转效果
          if (allSvg.active?.active_rotate?.val?.selectval) {
            allSvg.active.active_rotate.alarm.forEach((kk) => {
              if (eval(kk.expression.val)) {
                allSvg.extend_attr.rotate.val = kk.rotate.val.selectval;
              }
            });
          }
          //显示、隐藏
          if (allSvg.active?.active_show?.val?.selectval) {
            allSvg.active.active_show.alarm.forEach((kk) => {
              if (eval(kk.expression.val)) {
                allSvg.extend_attr.show.val = kk.show.val.selectval;
              }
            });
          }
          return;
        }
      }
    });
  });
};
</script>

<style lang="scss" scoped>
.iframe-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  
  &.is-iframe {
    // 在 iframe 中保持原有布局
    display: flex;
    flex-direction: column;
  }
}

.main_top {
  margin-bottom: 8px;
  border-radius: 8px;
  
  :deep(.el-card__body) {
    padding: 8px 12px;
  }
}

// 在 iframe 中让顶部工具栏自适应
.is-iframe .main_top {
  flex-shrink: 0;
}

.toolbar-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  
  .logo-section {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .logo-image {
      width: 45px;
      height: 45px;
      object-fit: contain;
    }
    
    .logo-text {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      letter-spacing: 1px;
    }
  }
  
  .left-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }
  
  .right-config {
    display: flex;
    gap: 8px;
    
    :deep(.el-form) {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 8px;
    }
    
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }
}

@media (max-width: 1200px) {
  .toolbar-section {
    flex-direction: column;
    align-items: stretch;
    
    .right-config {
      width: 100%;
    }
  }
}

.main {
  position: relative;
  width: 100%;
  height: calc(100vh - 67px);
  margin: 0 auto;
  overflow: hidden;
}

// 在 iframe 中自适应高度
.is-iframe .main {
  height: 100%;
  flex: 1;
  min-height: 0;
}

.editor-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.db_style {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 20vw;
  right: 20vw;
  z-index: 1000;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  overflow: auto;
  
  &::-webkit-scrollbar {
    width: 8px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    
    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

:deep(.template-list-dialog) {
  .el-dialog__body {
    padding: 20px;
    max-height: 70vh;
    overflow: hidden;
  }
  
  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #e4e7ed;
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .el-table {
    .el-table__body-wrapper {
      max-height: 50vh;
      overflow-y: auto !important;
    }
  }
}

:deep(.save-db-dialog) {
  .el-dialog__body {
    padding: 0 !important;
    overflow: visible !important;
  }
  
  .el-dialog__header {
    padding: 16px 20px;
    border-bottom: 2px solid #f0f0f0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    margin-bottom: 0;
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #ffffff;
    }
    
    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #ffffff;
        font-size: 22px;
        font-weight: 600;
        opacity: 0.9;
        
        &:hover {
          color: #ffffff;
          opacity: 1;
          transform: scale(1.1);
        }
      }
    }
  }
  
  .el-dialog__footer {
    padding: 0;
    border-top: none;
  }
}
</style>
